<?php
/**
 * TagsModel.php
 * TAG表操作
 * @author Life <349865361@qq.com>
 * @version 20140109
 */
class TagsModel extends BaseModel
{
    protected $table = 'tags';
    /**
     * 获取TAG表列表
     * @param string $condition 条件
     * @param int $limit 数量
     * @return array TAG表列表
     */
    public function loadData($condition = null, $limit = 20)
    {
        if(!empty($condition)){
            $condition='site = '.SITEID.' AND '.$condition;
        }else{
            $condition='site = '.SITEID;
        }
        return $this->select($condition, '', 'tag_id DESC', $limit);
    }
    /**
     * 获取TAG表总数
     * @param string $condition 条件
     * @return int 数量
     */
    public function countData($condition = null)
    {
        if(!empty($condition)){
            $condition='site = '.SITEID.' AND '.$condition;
        }else{
            $condition='site = '.SITEID;
        }
        return $this->count($condition);
    }
    /**
     * TAG信息
     * @param string $name TAG名称
     * @return array 用户信息
     */
    public function getInfoName($name)
    {
        return $this->find('site = '.SITEID.' AND name="' . $name . '"');
    }
    /**
     * 保存TAG表信息
     * @param array $data 页面表信息
     * @return bool 状态
     */
    public function saveData($data)
    {
        //格式化部分字段
        return $this->update('site = '.SITEID.' AND tag_id=' . $data['tag_id'], $data);
    }
    /**
     * 删除TAG表信息
     * @param int $tagsId TAG表ID
     * @return bool 状态
     */
    public function delData($tagId)
    {
        //删除关联内容
        return $this->delete('site = '.SITEID.' AND tag_id in(' . $tagId . ')');
    }
    /**
     * 数据格式化
     * @param array $data TAG信息
     * @return array 格式化后信息
     */
    public function foramtData($data)
    {
        return $data;
    }
    /**
     * 关联添加tag
     * @param array $data TAG信息
     * @return bool 状态
     */
    public function relationData($keywords, $contentId)
    {
        if (empty($keywords)) {
            return false;
        }
        $str = $keywords;
        $str = str_replace('，', ',', $str);
        $str = str_replace(' ', ',', $str);
        $strArray = explode(",", $str);
        //删除关联
        model('TagsRelation')->delDataContent($contentId);
        foreach ($strArray as $name) {
            if (empty($name)) {
                continue;
            }
            $info = $this->getInfoName($name);
            if (empty($info)) {
                //添加tag
                $data = array();
                $data['name'] = $name;
                $data['quote'] = 1;
                $data['site'] = SITEID;
                $tagId = $this->insert($data);
                //添加关联
                $relationData['content_id'] = $contentId;
                $relationData['tag_id'] = $tagId;
                model('TagsRelation')->addData($relationData);
            } else {
                //增加引用次数
                $data = array();
                $data['quote'] = intval($info['quote']) + 1;
                $data['tag_id'] = $info['tag_id'];
                $this->saveData($data);
                //查找关联
                $condition = array();
                $condition['content_id'] = $contentId;
                $condition['tag_id'] = $info['id'];
                $info_relation = model('TagsRelation')->getInfo($condition);
                //关联信息
                if (empty($info_relation)) {
                    $relationData = array();
                    $relationData['content_id'] = $contentId;
                    $relationData['tag_id'] = $info['tag_id'];
                    model('TagsRelation')->addData($relationData);
                }
            }
        }
        return true;
    }
    /**
     * 删除内容tag关联
     * @param array $data TAG信息
     * @return array 格式化后信息
     */
    public function delRelationData($contentId)
    {
        $list=model('TagsRelation')->loadDataContent($contentId);
        if(empty($list)){
            return;
        }
        //删除该内容的TAG关系
        model('TagsRelation')->delDataContent($contentId);
        //查找其他TAG关系
        foreach ($list as $value) {
            $info=model('TagsRelation')->getInfo('tag_id='.$value['tag_id']);
            if(empty($info)){
                $this->delData($value['tag_id']);
            }
        }
    }
    /**
     * 替换tag连接
     * @param array $data 数据内容
     * @param int $content_id 内容ID
     * @return string 处理后数据
     */
    public function replaceData($data,$content_id)
    {
        if(empty($data)){
            return $data;
        }
        $tagList=$this->model
                    ->field('A.*,B.*')
                    ->table('tags','A')
                    ->join('tags_relation','B',array('A.tag_id','B.tag_id'))
                    ->where('A.site = '.SITEID.' AND B.content_id='.$content_id)
                    ->select();
        if (!empty($tagList)) {
            $data=html_out($data);
            foreach ($tagList as $export) {
                if(!empty($export['name'])){
                    $data = preg_replace("/(?!<[^>]+)".preg_quote($export['name'],'/')."(?![^<]*>)/", '<a href="'.url('duxcms/Tags/index',array('name'=>$export['name'])).'"  target="_blank">'.$export['name'].'</a>',$data,1);
                }
            }
        }
        return $data;
    }

    /**
     * TAG列表标签
     * @param array $data 标签信息
     * @return array TAG列表
     */
    public function loadLabelList($data)
    {
        if(!empty($data['order'])){
            $data['order']=$data['order'].',';
        }
        if(!empty($data['name'])){
            $name=explode(',', $data['name']);

            $whereName='';
            foreach ($name as $value) {
                $whereName.=' OR name="'.$value.'" ';
            }
            $whereName=substr($whereName, 3);
        }
        if(empty($data['limit'])){
            $data['limit']=10;
        }
        $list = $this->loadData($whereName.$data['where'], $data['limit'],$data['order']);
        $data=array();
        if(!empty($list)){
            foreach ($list as $key => $value) {
                $data[$key]=$value;
                $data[$key]['url']=url('Tags/index',array('name'=>$value['name']));
            }
        }
        return $data;
    }
}